﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using NoResponseAlarm.Client.NoResponseAlarmService;
using System.Windows.Threading;
/*
www.gameland.ru (IIS)
www.xakep.ru (IIS)
www.xard.ru (IIS)
www.glc.ru (APACHE)
www.totalfootball.ru (APACHE)
www.socialist-company.com  (APACHE)
www.forum.xakep.ru (IIS)
*/
namespace NoResponseAlarm.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private class CheckTargetDef //TestTargetDef
        {
            public string Url { get; set; }
        }
        bool IsExecuting = false;
        string checkSource = "102.168.171.214"; //tester/checker/client

        DispatcherTimer timer;

        NoResponseAlarmService.NoResponseRegistrarClient client;
        private static CheckTargetDef[] checkTargetDefs = new CheckTargetDef[]{
            new CheckTargetDef(){Url = "http://gameland.ru"},
            new CheckTargetDef(){Url = "http://xakep.ru"},
            new CheckTargetDef(){Url = "http://xard.ru"},
            new CheckTargetDef(){Url = "http://glc.ru"},
            new CheckTargetDef(){Url = "http://totalfootball.ru"},
            new CheckTargetDef(){Url = "http://socialist-company.com"},
            new CheckTargetDef(){Url = "http://forum.xakep.ru"}
        };

        public MainWindow()
        {
            InitializeComponent();

            client = new NoResponseAlarmService.NoResponseRegistrarClient();
            
            timer = new DispatcherTimer();
            
            timer.Interval = TimeSpan.FromSeconds(5);

            // Set the callback to just show the time ticking away
            // NOTE: We are using a control so this has to run on 
            // the UI thread
            timer.Tick += new EventHandler((s,e)=>
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(PerformChecks));
                //Environment.TickCount
            });
            
            timer.Start();            

            //MessageBox.Show(CheckAvailability(url).ToString());
            //MessageBox.Show(CheckPing("www.gameland.ru").ToString());

        }
        private bool CanExecute
        {
            get { return !IsExecuting; }
        }

        //ExecuteTests/ExecuteChecks
        private void PerformChecks(object state) //PerformTests
        {
            IsExecuting = true;

            //Thread.Sleep(1000);

            foreach (CheckTargetDef def in checkTargetDefs)
            {
                CheckResult checkResult = Check(def.Url);

                CheckEventData eventData = new CheckEventData() { 
                    Source = checkSource,
                    Target = def.Url,
                    OperationResult = checkResult,
                    TimeStamp = DateTime.Now,
                    UserName = "dbo",
                    Extras = string.Empty };
                client.RegisterEvent(eventData);
            }
            IsExecuting = false;
        }
        private bool CheckPing(string url)
        {
            try
            {
                PingReply pingReply;
                using (var ping = new Ping())
                {
                    pingReply = ping.Send(url);
                    if (pingReply.Status == IPStatus.Success)
                    {
                        //IPStatus.DestinationUnreachable
                        return true;
                    }
                    //IPStatus.TimedOut
                }
            }
            catch (Exception ex)
            {
                //return false;
            }
            return false;
        }
        //Check if connection to site is available
        //TestsToPerform?
        private CheckResult Check(string url)
        {
            //CheckAvailability
            //string Message = string.Empty;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            // Set the credentials to the current user account
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.Method = "GET";
            //request.Method = "HEAD";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // Do nothing; we're only testing to see if we can get the response
                    if (response != null || response.StatusCode == HttpStatusCode.OK)
                    {
                        // HTTP = 200 - Internet connection available, server online
                        //response.ContentType == "text/html; charset=windows-1251"

                        return CheckResult.RequestSucceed;
                    }
                }
            }
            catch (WebException ex)
            {
                //return false;
            }

            return CheckResult.NoResponse;
        }
    }
}
